import { constantRoutes} from '@/router/index.js'
import { asyncRoutes} from '@/router/model.js'
import store from '@/store/index.js'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    //for(let i = 0;i<=roles.length;i++){
      return route.meta.roles.includes(roles)
   // }
    
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => { 
    const tmp = { ...route } 
      if (tmp.meta.roles.includes(roles)) {     
        if (hasPermission(roles, tmp)) {
          if (tmp.children) {       
             tmp.children = filterAsyncRoutes(tmp.children, roles)
          }
        res.push(tmp)
       } 
    }
  })
  // store.commit('SET_RES',res)
  return res
}

const state = {
  routes: [],
  addRoutes: [],
  code:'',
  res:[]
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_CODE: (state, CODE) => {
    state.code = CODE
  },
  SET_RES: (state, res) => {
    state.res = res
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('11111111')) {
        accessedRoutes = asyncRoutes || []
      }else{
        accessedRoutes = asyncRoutes || []
        // for(let i=0;i<asyncRoutes.length;i++){
        //   if(asyncRoutes.length==1){
        //     accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        //     break
        //   }
        //   let asyncRoute = [];
        //   asyncRoute.push(asyncRoutes[i])
        //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        
      // }
      
      }
       commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  setCode({commit},code){
     commit('SET_CODE',code)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
